package de.koller.oceanFramework.util;

import de.koller.oceanFramework.OceanException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

public class MIn {
	
	private PushbackInputStream in;
	
	public MIn( String file ) {
		try {
			in = new PushbackInputStream( new BufferedInputStream( new FileInputStream( file ) ) );
		} catch ( IOException ex ) {
			in = null;
			System.err.println( file + " not found, will only return 0" );
		}
	}

	public MIn( InputStream in ) {
		this.in = new PushbackInputStream( new BufferedInputStream( in ) );
	}
	
	public byte[] read( int length ) {
		try {
			byte[] data = new byte[ length ];
			in.read( data );
			return data;
		} catch ( Exception ex ) {
			return new byte[ length ];
		}
	}
	
	public int[] readInt( int length ) {
		int[] data = new int[ length ];
		for( int i = 0; i < length; i++ )
			data[i] = Bytnig.byteToInt( read( 4 ) );
		return data;
	}
	
	public long[] readLong( int length ) {
		long[] data = new long[ length ];
		for( int i = 0; i < length; i++ )
			data[i] = Bytnig.byteToLong( read( 8 ) );
		return data;
	}
	
	public float[] readFloat( int length ) {
		float[] data = new float[ length ];
		for( int i = 0; i < length; i++ )
			data[i] = Bytnig.byteToFloat( read( 4 ) );
		return data;
	}
	
	public double[] readDouble( int length ) {
		double[] data = new double[ length ];
		for( int i = 0; i < length; i++ )
			data[i] = Bytnig.byteToDouble( read( 8 ) );
		return data;
	}
	
	public String[] readUTF8String( int length ) {
		String[] data = new String[ length ];
		for( int i = 0; i < length; i++ ) {
			int sl = readInt( 1 )[0];
			byte[] d = read( sl );
			try {
				data[i] = new String( d, "latin1" );
			} catch( Exception ex ) {
				throw new OceanException( ex );
			}
		}
		return data;
	}
	
	public String[] readString( int length ) {
		String[] data = new String[ length ];
		for( int i = 0; i < length; i++ ) {
			int sl = readInt( 1 )[0];
			byte[] d = read( sl );
			data[i] = new String( d );
		}
		return data;
	}
	
	/** Liest und vergleicht die angegebenen bytes. Sollten sie nicht übereinstimmen
	 *  wird zurück auf die Position gesprungen wo es vor dem Aufruf war und false zurückgegeben.
	 *  Sinnvoll um zu prüfen ob ein bestimmter Punkt erreicht wurde. */
	public boolean check( byte... eoc ) {
		try {
			byte[] r = read( eoc.length );
			for( int i = 0; i < eoc.length; i++ )
				if( r[i] != eoc[i] ) {
					in.unread( r );
					return false;
				}
			
			return true;
		} catch( IOException ex ) {
			return false;
		}
	}
	
	public void close() {
		try {
			in.close();
		} catch ( Exception ex ) { }
	}
	
}
